package controller;

import api.LoginApi;
import common.pojo.CommonResult;
import common.spring.redis.RedisUnits;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.WxUserInfo;
import service.LoginService;
import service.WxUserInfoService;
import utils.JsonUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by asus on 2018/10/4.
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController extends ManagerBaseController {
    private final Logger LOG = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    LoginService service;
    @Autowired
    RedisUnits redisUnits;
    @Autowired
    LoginApi loginApi;
    @Autowired
    WxUserInfoService infoService;

    /**
     * wx.getUserInfo接口解析并存储用户信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(
            HttpServletRequest request
    ) {
        Map map = parseRequestParamMap(request);
        LOG.warn("---login---" + JsonUtil.toJson(map));
        if (map.size() == 0) {
            return CommonResult.returnFailsWrapper("登录失败");
        }
        if (!map.containsKey("code")) {
            return CommonResult.returnFailsWrapper("请传入code");
        }
        if (!map.containsKey("detail")) {
            return CommonResult.returnFailsWrapper("请传入detail");
        }
        String parentOpenId = "";
        if (map.containsKey("parentOpenId")) {
            try {
                if (StringUtils.isNotBlank(map.get("parentOpenId").toString())) {
                    Map parent = redisUnits.getMap(map.get("parentOpenId").toString());
                    if (map == null) {
                        return new CommonResult(4, "该分享连接已失效");
                    }
                    parentOpenId = parent.get("openId").toString();
                } else {
                    parentOpenId = "clkj";
                }
            } catch (Exception e) {
                LOG.warn("e--Exception-" + e.toString());
                LOG.warn("e--Exception-" + e.toString());
            }

        } else {
            parentOpenId = "clkj";
        }
        if(map.containsKey("parentId")){
         if(StringUtils.isNotBlank(map.get("parentId").toString()) && NumberUtils.toLong(map.get("parentId").toString())>0){
            WxUserInfo wxUserInfo = infoService.getWxUserInfo(NumberUtils.toLong(map.get("parentId").toString()));
            if(wxUserInfo!=null){
                parentOpenId=wxUserInfo.getOpenId();
            }
         }
        }
        String recommendOpenId = "";
        if (map.containsKey("recommendOpenId")) {
            try {
                if (StringUtils.isNotBlank(map.get("recommendOpenId").toString())) {
                    Map parent = redisUnits.getMap(map.get("recommendOpenId").toString());
                    if (map == null) {
                        return CommonResult.returnFailsWrapper("该分享连接已失效");
                    }
                    LOG.warn(JsonUtil.toJson(parent));
                    recommendOpenId = parent.get("openId").toString();
                } else {
                    recommendOpenId = "";
                }
            } catch (Exception e) {
                LOG.warn("e--Exception-" + e.toString());
                LOG.warn("e--Exception-" + e.toString());
            }
        }
        return service.login(map, parentOpenId, recommendOpenId);
    }

    @RequestMapping(value = "/phone", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult getPhone(HttpServletRequest request) {
        Map map = parseRequestParamMap(request);
        String sessionId = request.getHeader("sessionId");
        if (StringUtils.isBlank(sessionId)) {
            return new CommonResult(3, "重新登录");
        }
        Map userMap = redisUnits.getMap(sessionId);
        if (userMap == null) {
            return new CommonResult(3, "重新登录");
        }
        Map phone = new HashMap();
        try {
            phone = loginApi.getPhone(map.get("encryptedData").toString(), userMap.get("sessionKey").toString(), map.get("iv").toString());
        } catch (Exception e) {
            return new CommonResult(3, "重新登录");
        }

        String phoneNumber = phone.get("purePhoneNumber").toString();
        int num = infoService.updatePhone(phoneNumber, userMap.get("openId").toString());
        if (num <= 0) {
            return CommonResult.returnFailsWrapper("开店失败");
        }
        return CommonResult.returnDataWrapper(phone);
    }
}